var opts = {
    container: 'epiceditor',
    textarea: null,
    basePath: '',
    clientSideStorage: false,
    localStorageName: 'epiceditor',
    useNativeFullscreen: true,
    parser: marked,
    file: {
        name: 'epiceditor',
        defaultContent: '',
        autoSave: 100
    },
    theme: {
        base: '/static/xBlog_admin/epiceditor/themes/base/epiceditor.css',
        preview: '/static/xBlog_admin/epiceditor/themes/preview/github.css',
        editor: '/static/xBlog_admin/epiceditor/themes/editor/epic-dark.css'
    },
    button: {
        preview: true,
        fullscreen: true,
        bar: "auto"
    },
    focusOnLoad: false,
    shortcut: {
        modifier: 18,
        fullscreen: 70,
        preview: 80
    },
    string: {
        togglePreview: 'Toggle Preview Mode',
        toggleEdit: 'Toggle Edit Mode',
        toggleFullscreen: 'Enter Fullscreen'
    },
    autogrow: false
};
var csrf_token = null;
var editor = null;
$(function () {
    csrf_token = Cookies.get('csrftoken');
    $('input.csrfmiddlewaretoken').val(csrf_token);
});

function add_tag(self) {
    var lang = self.firstElementChild.textContent;
    self.parentNode.removeChild(self);
    var tag = $('<label class="article-tags animated zoomIn" title="' + lang + '" style="margin-right: 4px;" ondblclick="remove_tag(this)"><span class="tag glyphicon glyphicon-tag">' + lang + '</span></label>')[0];
    var tagList = $('.selector')[0];
    tagList.insertBefore(tag, $('#tags-available_div')[0]);
}

function init_add_tag(lang) {
    var tag = $('<label class="article-tags animated zoomIn" title="' + lang + '" style="margin-right: 4px;" ondblclick="remove_tag(this)"><span class="tag glyphicon glyphicon-tag">' + lang + '</span></label>')[0];
    var tagList = $('.selector')[0];
    tagList.insertBefore(tag, $('#tags-available_div')[0]);
}

function remove_tag(self) {
    if (!$(self).hasClass("animated")) {
        $(self).addClass("animated");
    }
    $(self).removeClass("zoomIn").addClass("hinge");
    setTimeout(function () {
        var lang = self.firstElementChild.textContent;
        self.parentNode.removeChild(self);
        var tag = $('<label class="available-tags" title="' + lang + '" style="margin-right: 4px;" onclick="add_tag(this)"><span class="tag glyphicon glyphicon-tag">' + lang + '</span></label>')[0];
        var tagAvailableList = $('#tagAvailableList')[0];
        tagAvailableList.appendChild(tag);
    }, 1800);
}

function saveArticle(article_id) {
    save(article_id, '/blog_articles/');
}

function saveArticleContinueEdit(article_id) {
    save(article_id, null);
}

function saveArticleAddNew(article_id) {
    save(article_id, '/blog_articles/add/');
}

function save(article_id, href) {
    var tags = [];
    var spans = $('.selector label.article-tags span');
    for (var i = 0; i < spans.length; i++) {
        tags.push(spans[i].textContent);
    }
    $.ajax({
        url: "/save_article/",
        type: "POST",
        data: {
            csrfmiddlewaretoken: csrf_token,
            id: article_id,
            title: $('#id_title').val(),
            catagory: $('#id_catagory').val(),
            archive: $('#id_archive').val(),
            tags: JSON.stringify(tags),
            content: editor.exportFile(),
        },
        dataType: "json",//json--返回json数据类型；xml--返回xml
        success: function (msg) {
            if (!msg.result) {
                alert('修改失败: ' + msg.message);
            }
            else {
                alert('修改成功');
                cleanStorage();
                if (href) {
                    window.location.href = href;
                }
            }
        }
    });
}

var localStorageTimer = null;

function initAddPage() {
    if (!window.localStorage) {
        alert('大鹌鹑建议您使用Chrome或Firefox等支持localStorage的主流浏览器使用本系统。\n您使用此非主流浏览器畅游互联网对您的身心健康无益请谨慎使用！"');
    }
    else {
        var title = window.localStorage.getItem('article_title');
        if (title) {
            $('#id_title').val(title);
        }
        var catagory = window.localStorage.getItem('article_catagory');
        if (catagory) {
            $('#id_catagory').val(catagory);
        }
        var archive = window.localStorage.getItem('article_archive');
        if (archive) {
            $('#id_archive').val(archive);
        }
        var content = window.localStorage.getItem('article_content');
        if (editor && content) {
            editor.importFile(null, content);
        }
        var tags = eval(window.localStorage.getItem('article_tag'));
        if (tags) {
            for (var i = 0; i < tags.length; i++) {
                init_add_tag(tags[i]);
                var tag = $('#tagAvailableList label[title=' + tags[i] + ']')[0];
                tag.parentElement.removeChild(tag);
            }
        }
        localStorageTimer = setInterval(function () {
            window.localStorage.setItem('article_title', $('#id_title').val());
            window.localStorage.setItem('article_catagory', $('#id_catagory').val());
            window.localStorage.setItem('article_archive', $('#id_archive').val());
            if (editor) {
                window.localStorage.setItem('article_content', editor.exportFile());
            }
            var tags = [];
            var spans = $('.selector label.article-tags span');
            for (var i = 0; i < spans.length; i++) {
                tags.push(spans[i].textContent);
            }
            window.localStorage.setItem('article_tag', JSON.stringify(tags));
        }, 100);
    }
}

function cleanStorage() {
    if (window.localStorage) {
        clearInterval(localStorageTimer);
        window.localStorage.removeItem('article_title');
        window.localStorage.removeItem('article_catagory');
        window.localStorage.removeItem('article_archive');
        window.localStorage.removeItem('article_content');
        window.localStorage.removeItem('article_tag');
    }
}